package com.qf.barrier;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CuratorBarrier2 {
    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);//用作阻塞的, 1 的意思是只需有一个地方执行了放行就放行所有阻塞的地方

    private static DistributedBarrier distributedBarrier;

    public static void main(String[] args) throws Exception {

        for (int i = 0; i < 10; i++) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
                                .connectString(ZKADDR)
                                .connectionTimeoutMs(5000)
                                .retryPolicy(new ExponentialBackoffRetry(1000, 5))
                                .build();
//                    开始连接
                        curatorFramework.start();

                        distributedBarrier=new DistributedBarrier(curatorFramework, "/tianjing");
//                        各就各位准备开枪
                        System.err.println(Thread.currentThread().getName()+"准备了");
                        distributedBarrier.setBarrier();
//                      等待开枪
                        distributedBarrier.waitOnBarrier();
                        System.err.println("开始比赛了");


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

        Thread.sleep(5000);
//        信号元开枪了
        System.out.println("信号源1");
        distributedBarrier.removeBarrier();
        System.out.println("信号源2");

        System.in.read();


    }

}
